package algorithms.sorting

/**
 * [Big Sorting](https://www.hackerrank.com/challenges/big-sorting)
 * 第六个Case 只是读取Input就会超时
 */
// Complete the bigSorting function below.
fun bigSorting(unsorted: Array<String>): Array<String> {

    val size = unsorted.size
    val groups = LinkedHashMap<String, Int>(size)

    unsorted.forEach {
        groups[it] = groups.getOrDefault(it, 0).plus(1)
    }

    val comparator = Comparator<String> { o1, o2 ->
        val r = o1.length.compareTo(o2.length)
        if (r == 0) o1.compareTo(o2) else r
    }

    val sortedKeys = groups.keys.sortedWith(comparator)

    var i = 0
    for (key in sortedKeys) {
        val count = groups[key]!!
        for (j in 0 until count) {
            unsorted[i] = key
            i++
        }
    }

    return unsorted
}